package io.renren.modules.app.controller;

import io.renren.common.utils.StatusConstant;
import io.renren.modules.app.entity.DomainEntity;
import io.renren.modules.app.service.DomainService;
import io.renren.modules.app.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Controller
public class AppDomainPageController {

    @Autowired
    private DomainService domainService;

    @GetMapping("/page/error")
    public String error() {
        return "error";
    }

    @GetMapping("/page/{domain}")
    public ModelAndView domainPage(@PathVariable String domain, HttpServletResponse response) throws Exception {
        if(domain.isEmpty()){
            throw new Exception("未找到主域名");
        }


        DomainEntity domainEntity = domainService.queryByDomain(domain);
        // 校验主域名状态
        int domainStatus = domainEntity.getStatus();
        if(StatusConstant.DISABLE == domainStatus){
            // 主域名未开启，直接跳到错误页面
            return new ModelAndView("redirect:error");
        }

        List<DomainEntity> domainList = domainService.queryDomainListByParentId(domainEntity.getId());
        // shuffle 打乱顺序
        Collections.shuffle(domainList);
        DomainEntity subDomain = domainList.get(0);

        if(StatusConstant.DISABLE == subDomain.getStatus()){
            return new ModelAndView("redirect:error");
        }else{
            return new ModelAndView(new RedirectView(subDomain.getDomain()));
//            if(StatusConstant.ENABLE == subDomain.getIsLuodi()){
//                return new ModelAndView("Method…");
//            } else {
//                return new ModelAndView(new RedirectView(subDomain.getDomain()));
//            }

        }

    }


    @GetMapping("/luodi/{index}")
    public ModelAndView luodiPage(@PathVariable String index) throws Exception {
        if(index.isEmpty()){
            throw new Exception("");
        }
        return new ModelAndView(new RedirectView("http://baidu.com"));
    }

}
